<template>
  <div>
    <group style="margin:-20px 0 0 0">
      <x-input title="用户名" :value.sync="username"></x-input>
      <x-input title="密码" :value.sync="password" type="password"></x-input>
      <x-button @click="onLoginClick">登陆
        <x-button>
    </group>
  </div>
</template>

<script>
  import Group from 'vux/dist/components/group'
  import XInput from 'vux/dist/components/x-input'
  import XButton from 'vux/dist/components/x-button'

  export default {
    components: {
      Group,
      XInput,
      XButton
    },
    data() {
      return {
        username: '',
        password: ''
      }
    },
    ready() {
      if (this.isLoggedIn)
        this.$router.go('/')
    },
    methods: {
      onLoginClick() {
        this.$dispatch('loading', {
          show: true
        })
        axios.post('/login.do', {
          username: this.username,
          password: this.password
        }).then(result => {
          this.$dispatch('loading', {
            show: false
          })
          if (result.data.result == 1) {
            this.setIsLoggedIn(true)
            this.$router.go('/')
          }
        }, (response) => {
          this.$dispatch('loading', {
            show: false
          })
          console.log(response)
        })
      }
    },
    vuex: {
      getters: {
        isLoggedIn(state) {
          return state.isLoggedIn
        }
      },
      actions: {
        setIsLoggedIn({dispatch}, isLoggedIn) {
          dispatch('setIsLoggedIn', isLoggedIn)
        }
      }
    }
  }
</script>
